package com.ck.common.aspect;

import com.alibaba.fastjson.JSONObject;
import com.ck.common.aspect.annotation.Dict;
import com.ck.common.constant.DictEnum;
import com.ck.util.CommonConstant;
import com.ck.util.R;
import com.ck.util.oConvertUtils;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 字典aop类
 * @Author: ck
 * @Date: 2022年10月25日10:39:59
 * @Version: 1.0
 */
@Aspect
@Component
@Slf4j
public class DictAspect {

    @Pointcut("execution(public * com.ck.controller.*Controller.*(..))")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long time1=System.currentTimeMillis();
        Object result = pjp.proceed();
        long time2=System.currentTimeMillis();
        log.info("获取JSON数据 耗时："+(time2-time1)+"ms");
        long start=System.currentTimeMillis();
        this.parseDictText(result);
        long end=System.currentTimeMillis();
        log.info("解析注入JSON数据  耗时"+(end-start)+"ms");
        return result;
    }

    private void parseDictText(Object result) {
        if (result instanceof R) {
            Object record = ((R<?>) result).getResult();
            if(record instanceof String) {
                return;
            }
            ObjectMapper mapper = new ObjectMapper();
            String json="{}";
            try {
                json = mapper.writeValueAsString(record);
            } catch (JsonProcessingException e) {
                log.error("json解析失败"+e.getMessage(),e);
            }
            //当前实体类转JSONObject
            JSONObject item = JSONObject.parseObject(json);
            fieldIterator(record, item);
            ((R<JSONObject>) result).setResult(item);
        }
    }

    /**
     *
     * @param record R中的result对象
     * @param item 把result中的对象转为json对象JSONObject
     */
    private void fieldIterator(Object record,JSONObject item){
        //field为result对象中每一个字段
        for (Field field : oConvertUtils.getAllFields(record)) {
            if (field.getAnnotation(Dict.class) != null) {
                String code = field.getAnnotation(Dict.class).dicCode();
                String text = field.getAnnotation(Dict.class).dicText();
                String table = field.getAnnotation(Dict.class).dictTable();
                String type = field.getAnnotation(Dict.class).dictType();
                String key = String.valueOf(item.get(field.getName()));
                log.info("type:{}",type);
                if(item.get(field.getName()) != null) {
                    if(type.equals("list") && !(record instanceof String) ) {
//                        List<?> recordList = (List<?>) record;
//                        List<JSONObject> jsonObjects = parseListDictText(recordList);
//                        item.put(field.getName(), jsonObjects);
                    }else {
                        //翻译字典值对应的txt
                        String textValue = translateDictValue(code, text, table, key);

                        log.debug(" 字典Val : "+ textValue);
                        log.debug(" __翻译字典字段__ "+field.getName() + CommonConstant.DICT_TEXT_SUFFIX+"： "+ textValue);
                        item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                    }
                }
            }
            //date类型默认转换string格式化日期
            if (field.getType().getName().equals("java.util.Date")&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){
                SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
            }
        }
    }

    private List<JSONObject> parseListDictText(List<?> result) {
        List<JSONObject> items = new ArrayList<>();
        for (Object record : result) {
            ObjectMapper mapper = new ObjectMapper();
            String json="{}";
            try {
                //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                json = mapper.writeValueAsString(record);
            } catch (JsonProcessingException e) {
                log.error("json解析失败"+e.getMessage(),e);
            }
            JSONObject item = JSONObject.parseObject(json);
            //update-begin--Author:scott -- Date:20190603 ----for：解决继承实体字段无法翻译问题------
            //for (Field field : record.getClass().getDeclaredFields()) {
            for (Field field : oConvertUtils.getAllFields(record)) {
                //update-end--Author:scott  -- Date:20190603 ----for：解决继承实体字段无法翻译问题------
                if (field.getAnnotation(Dict.class) != null) {
                    String code = field.getAnnotation(Dict.class).dicCode();
                    String text = field.getAnnotation(Dict.class).dicText();
                    String table = field.getAnnotation(Dict.class).dictTable();
                    String key = String.valueOf(item.get(field.getName()));

                    //翻译字典值对应的txt
                    String textValue = translateDictValue(code, text, table, key);

                    log.debug(" 字典Val : "+ textValue);
                    log.debug(" __翻译字典字段__ "+field.getName() + CommonConstant.DICT_TEXT_SUFFIX+"： "+ textValue);
                    item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                }
                //date类型默认转换string格式化日期
                if (field.getType().getName().equals("java.util.Date")&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){
                    SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                }
            }
            items.add(item);
        }
        return items;
    }

    private String translateDictValue(String code, String text, String table, String key) {
        if(oConvertUtils.isEmpty(key)) {
            return null;
        }

        StringBuffer textValue=new StringBuffer();
        String tmpValue = null;
        if (!StringUtils.isEmpty(table)){
        }else {
            DictEnum.getValue(code, key);
        }
        if (tmpValue != null) {
            if (!"".equals(textValue.toString())) {
                textValue.append(",");
            }
            textValue.append(tmpValue);
        }
        return textValue.toString();
    }
}
